package com.itheima.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.OrdersService;
import com.itheima.bean.Orders;
import com.itheima.bean.Params;
import com.itheima.bean.R;
import com.itheima.config.ThreadLocalConfig;
import com.itheima.dto.OrdersDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RequestMapping("/order")
@RestController
public class OrdersController {
    @Autowired
    private OrdersService ordersService;


    @GetMapping("/userPage")
    public R userOrders(Params param){
        IPage<OrdersDto> dtoIPage=  ordersService.findUserOrders(param);
        return R.success(dtoIPage);
    }

    @GetMapping("/page")
    public R find(int page, int pageSize, String number, String beginTime,String endTime){
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date begin =null;
            Date end =null;
            if (beginTime!=null){
                begin = simpleDateFormat.parse(beginTime);
            }
            if (endTime!=null){
                end= simpleDateFormat.parse(endTime);
            }


            IPage<Orders> ordersIPage=ordersService.fingPage(page,pageSize,number,begin,end);
            return R.success(ordersIPage);
        } catch (ParseException e) {
            e.printStackTrace();
            return R.error("查询失败！");
        }

    }


    @PostMapping("/submit")
    public R add(@RequestBody Orders orders){
        Long userId = ThreadLocalConfig.get();
        orders.setUserId(userId);
       int row= ordersService.add(orders);
       if (row>0){
           return R.success("订单增加成功！");
       }return R.error("订单增加失败！");
    }
}
